<template>
  <n-card :border="false">
    <n-alert :show-icon="false" class="m-b-10">
      <n-form :model="search_param" class="search-forms"
              inline
              :show-feedback="false"
              label-placement="left"
              @keydown.enter.prevent="handleSubmitSearch">
        <n-form-item label="昵称/电话">
          <n-input v-model:value="search_param.key" placeholder="输入昵称或电话号码查询" clearable/>
        </n-form-item>
        <n-form-item label="性别">
          <n-select v-model:value="search_param.sex" :options="sexOption" style="width: 130px;" clearable/>
        </n-form-item>
        <n-form-item label="状态">
          <n-select v-model:value="search_param.status" :options="statusOption" style="width: 130px;" clearable/>
        </n-form-item>
        <n-form-item>
          <search-button-group @submit="handleSubmitSearch"
                               @reset="()=>(search_param.key=null,search_param.status=null,search_param.sex=null)"/>
        </n-form-item>
      </n-form>
    </n-alert>
    <data-table ref="data_list"
                :columns="columns"
                :action-column="actionColumn"
                :row-key="(row:Recordable) => row.id"
                :params="search_param"
                list-url="user/list" default-selection @update:checked="checkedUsers">
      <template #toolbarLeft>
        <n-button type="success" v-permission="['teacher:add']" @click="showUserVipSetting">
          用户VIP设定
        </n-button>
      </template>
    </data-table>
  </n-card>
  <!--修改用户信息-->
  <n-modal v-model:show="addEditModel"
           title="修改用户信息" :mask-closable="false"
           :show-icon="false" preset="dialog" style="width: 560px;" @after-leave="closeAddEditModel">
    <n-form ref="addEditFormRef" :model="addEditForm" require-mark-placement="left"
            label-width="auto" label-placement="left">
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="8" label="昵称:">
          {{ addEditForm.nickname }}
          <!--           <n-input v-model:value="addEditForm.nickname" readonly/>-->
        </n-form-item-gi>
        <n-form-item-gi :span="4" label="ID:" :label-width="40">
          {{ addEditForm.id }}
        </n-form-item-gi>
        <n-form-item-gi :span="8" label="头像:" style="position: absolute;right: 10px;">
          <div>
            <div class="select-img" style="width: 100px;height: 100px;border:none;"
                 :class="appStore.theme=='light'?'light-img':'dark-img'">
              <div class="select-img-img">
                <template v-if="addEditForm.avatar">
                  <n-image
                      width="100"
                      :src="Config.VIEW_FILE+addEditForm.avatar"
                  />
                </template>
              </div>
            </div>
          </div>
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="12" label="出生日期:">
          <n-date-picker v-model:value="addEditForm.birthdayStamp" type="date" @update:value="confirmBirthday"/>
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="12" label="性别:">
          <n-radio-group v-model:value="addEditForm.sex" name="sex">
            <n-radio :key="1" :value="1" label="男性"/>
            <n-radio :key="2" :value="2" label="女性"/>
            <n-radio :key="0" :value="0" label="未知"/>
          </n-radio-group>
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="12" label="电话:">
          <n-input v-model:value="addEditForm.phone" maxlength="11" placeholder="用户电话号码" clearable/>
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="12" label="余额:">
          <n-input-group>
            <n-input-number v-model:value="addEditForm.money" disabled :min="0" :precision="2" :show-button="false"
                            placeholder="用户余额、请谨慎操作" clearable/>
            <n-input-group-label>元</n-input-group-label>
          </n-input-group>
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="12" label="积分:">
          <n-input-number v-model:value="addEditForm.integral" :min="0" :precision="2" :show-button="false"
                          style="width: 100%" placeholder="用户积分" clearable/>
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="20" label="简介:">
          <n-input
              v-model:value="addEditForm.intro"
              type="textarea"
              placeholder="用户简介"
              :autosize="{minRows: 3}"/>
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="12" label="状态:">
          <n-switch :round="false" v-model:value="addEditForm.status" :checked-value="1" :unchecked-value="0">
            <template #checked>
              正常
            </template>
            <template #unchecked>
              禁用
            </template>
          </n-switch>
        </n-form-item-gi>
      </n-grid>
    </n-form>
    <template #action>
      <n-space>
        <n-button @click="()=>(addEditModel=false)">取消</n-button>
        <n-button type="primary" :loading="handelSubmitLoading" @click="handelSubmitData">确定</n-button>
      </n-space>
    </template>
  </n-modal>
  <!--修改用户余额-->
  <n-modal v-model:show="userMoneyModel" title="修改用户余额"
           :mask-closable="false" :show-icon="false" preset="dialog" @after-leave="closeUserMoneyModel"
           style="width: 560px">
    <n-alert type="warning" class="alert_small m-b-10">
      温馨提示：输入的金额不会直接修改用户余额，只会加减余额
    </n-alert>
    <n-form ref="userMoneyFormRef" :model="userMoneyForm" :rules="userMoneyFormRules" require-mark-placement="left"
            label-width="auto" label-placement="left">
      <n-grid :cols="24" :x-gap="24">
        <n-form-item-gi :span="10" label="用户名称:" path="userName">
          {{ userMoneyForm.userName }}
        </n-form-item-gi>
        <n-form-item-gi :span="10" label="头像:">
          <div style="width: 100px;height: 100px;position: absolute;top: 5px;">
            <n-image
                width="100" style="border-radius: 3px;"
                :src="Config.VIEW_FILE+userMoneyForm.avatar"
            />
          </div>
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="10" label="当前余额:">
          {{ userMoneyForm.originalBalance.toFixed(2) }}元
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="10" label="类型:" path="type">
          <n-select v-model:value="userMoneyForm.type" :options="typeOption" placeholder="请选择类型" clearable/>
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="20" label="余额:" path="money">
          <div>
            <n-input-number v-model:value="userMoneyForm.money" :min="0" :precision="2" :show-button="false"
                            style="width: 100%"
                            placeholder="请输入金额" clearable/>
          </div>
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="20" label="原由:" path="remark">
          <n-input
              v-model:value="userMoneyForm.remark"
              type="textarea"
              placeholder="请输入原由"
              :autosize="{ minRows: 3}"/>
        </n-form-item-gi>
      </n-grid>
    </n-form>
    <template #action>
      <n-space>
        <n-button @click="()=>(userMoneyModel=false)">取消</n-button>
        <n-button type="primary" :loading="userMoneyHandelSubmitLoading" @click="handelSubmitUserMoney">确定</n-button>
      </n-space>
    </template>
  </n-modal>
  <!-- 用户vip设定 -->
  <n-modal v-model:show="userVipModel"
           title="用户vip设定" :mask-closable="false"
           :show-icon="false" preset="dialog" style="width: 560px;"
           @after-leave="()=>(userVipForm.uId=[],userVipForm.vipId=null,userVipForm.remark=null,userVipForm.price=null,handelUserVipSubmitLoading=false)">
    <n-form ref="userVipFormRef" :model="userVipForm" require-mark-placement="left"
            :label-width="60" label-placement="left">
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="12" label="vip:" path="vipId" :rule="{
          type:'number',
          required: true,
        message: '请选择vip',
        trigger: ['blur', 'change']
      }">
          <n-select v-model:value="userVipForm.vipId" :options="vipOptions" placeholder="请选择vip" clearable/>
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="12" label="价格:">
          <div>
            <n-input-number v-model:value="userVipForm.price" :show-button="false" :min="0" :precision="2"
                            placeholder="用户vip设定价格" clearable/>
            <p class="tips_p">相当于用户付款的金额</p>
          </div>
        </n-form-item-gi>
      </n-grid>
      <n-grid :cols="20" :x-gap="24">
        <n-form-item-gi :span="20" label="备注:">
          <n-input
              v-model:value="userVipForm.remark"
              type="textarea"
              placeholder="备注"
              :autosize="{minRows: 3}"/>
        </n-form-item-gi>
      </n-grid>
    </n-form>
    <template #action>
      <n-space>
        <n-button @click="()=>(userVipModel=false)">取消</n-button>
        <n-button type="primary" :loading="handelUserVipSubmitLoading" @click="saveUserVip">确定</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script setup lang="ts">
import {h, reactive, ref, onMounted,computed} from 'vue';
import SearchButtonGroup from '@components/SearchButtonGroup';
import {FormInst, FormItemRule, NAvatar, NImage, NPopconfirm, NTag, SelectOption, useMessage} from 'naive-ui';
import DataTable from '@components/DataTable';
import DataTableAction from '@components/DataTable/src/components/DataTableAction';
import {UseAppStore} from '@/stores/app.ts';
import {Config} from "@/config";
import {delRequest, postPutRequest, getRequest} from "@/api/data.ts";

const message = useMessage()
const appStore = UseAppStore();

const statusOption = ref<SelectOption[]>([
  {
    label: '正常',
    value: 1,
  }, {
    label: '禁用',
    value: 0,
  }
])
const typeOption = ref<SelectOption[]>([
  {
    label: '加',
    value: 0,
  }, {
    label: '减',
    value: 1,
  }
])
const sexOption = ref<SelectOption[]>([
  {
    label: '男',
    value: 1,
  }, {
    label: '女',
    value: 2,
  }, {
    label: '未知',
    value: 0,
  }
])
const search_param = ref({
  key: null,
  status: null,
  sex: null,
})
//数据表
const data_list = ref<any>();
const columns = ref([
  {
    title: 'ID',
    key: 'id',
    width: 70,
    align: 'center',
  },
  {
    title: '头像',
    key: 'avatar',
    width: 60,
    align: 'center',
    render(row: { avatar: string }) {
      if (row.avatar) {
        return h(NAvatar, {
          size:30,
          src:  Config.VIEW_FILE + row.avatar
        })
      }
    }
  }, {
    title: '昵称',
    key: 'nickname',
    minWidth:100
  }, {
    title: '电话',
    key: 'phone',
    width: 150
  }, {
    title: '余额(元)',
    key: 'money',
    width: 130,
    align: 'center',
    render(row: { money: number }) {
      return h('span', null, {default: () => (row.money.toFixed(2))})
    }
  }, {
    title: '累计提现(元)',
    key: 'totalWithdrawal',
    width: 130,
    align: 'center',
    render(row: { totalWithdrawal: number }) {
      return h('span', null, {default: () => (row.totalWithdrawal.toFixed(2))})
    }
  },
  // {
  //   title: '积分',
  //   key: 'integral',
  //   width: 130,
  //   align: 'center',
  //   render(row: { integral: number }) {
  //     return h('span', null, {default: () => (row.integral.toFixed(2))})
  //   }
  // },
  {
    title: '性别',
    key: 'sex',
    width: 80,
    align: 'center',
    render(row: { sex: boolean | number }) {
      const genderText = row.sex == 1 ? '男' : row.sex == 2 ? '女' : '未知';
      return h('span', null, {default: () => (genderText)})
    }
  }, {
    title: '出生日期',
    key: 'birthday',
    width: 100,
    align: 'center',
  }, {
    title: 'VIP',
    key: 'vip',
    width: 80,
    align: 'center',
    render(row: { vip: boolean | number }) {
      const enabled_color = row.vip ? 'success' : 'default';
      const enabled_text = row.vip ? 'VIP' : '普通';
      return h(NTag,
          {
            type: enabled_color,
          },
          {
            default: () => (enabled_text),
          }
      );
    }
  },{
    title: 'VIP类型',
    key: 'vipName',
  }, {
    title: '状态',
    key: 'status',
    width: 80,
    align: 'center',
    render(row: { status: boolean | number }) {
      const enabled_color = row.status ? 'success' : 'warning';
      const enabled_text = row.status ? '正常' : '禁用';
      return h(NTag,
          {
            type: enabled_color,
          },
          {
            default: () => (enabled_text),
          }
      );
    }
  }, {
    title: '创建时间',
    key: 'createTime',
    width: 175,
  }
]);
//操作列
const actionColumn = reactive({
  width: 170,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record: Recordable) {
    return h(DataTableAction, {
      actions: [
        {
          label: '余额',
          onClick: handelEditUserMoney.bind(null, record),
          type: 'primary',
          permission: ['user:edit']
        },
        {
          label: '修改',
          onClick: handleEdit.bind(null, record),
          type: 'primary',
          permission: ['user:edit']
        },
        {
          label: '删除',
          type: 'error',
          popConfirm: NPopconfirm,
          onPositiveClick: handleDelete.bind(null, record),
          confirm: {
            text: '确定删除当前用户吗？',
          },
          permission: ['user:del']
        },
      ]
    });
  },
});
//编辑用户
const addEditModel = ref<boolean>(false);
const addEditFormRef = ref<FormInst | null>(null);
const handelSubmitLoading = ref<boolean>(false);
const addEditForm = ref({
  id: 0,
  nickname: null,
  phone: null,
  sex: <number | null>null,
  avatar: null,
  birthday: <string | null>null,
  integral: <number | null>null,
  money: <number | null>null,
  status: 0,
  intro: null,
  totalWithdrawal: null,
  birthdayStamp: <number | null>null,
})
//修改用户余额
const userMoneyModel = ref<boolean>(false);
const userMoneyFormRef = ref<FormInst | null>(null);
const userMoneyHandelSubmitLoading = ref<boolean>(false);
const userMoneyForm = ref({
  userId: 0,
  userName: null,
  avatar: null,
  money: null,
  originalBalance: 0,
  remark: null,
  type: null,
})
const userMoneyFormRules = computed(() => {
  return {
    money: {
      type: 'number',
      required: true,
      trigger: ['blur', 'input'],
     // message: '请输入金额',
      validator: (_rule: FormItemRule, value: number) => {
        return new Promise<void>((resolve, reject) => {
          if (!value) {
            reject(Error("请输入金额"));
          } else if (userMoneyForm.value.type && userMoneyForm.value.type ===1 && value &&  userMoneyForm.value.originalBalance < value) {
            reject(Error("扣除金额不得大于用户现有的金额"));
          } else {
            resolve();
          }
        });
      },
    },
    type: {
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择类型'
    },
    remark: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入原由'
    }
  }
})

//设定用户vip
const vipOptions = ref<SelectOption[]>([])
const userVipModel = ref<boolean>(false);
const userVipFormRef = ref<FormInst | null>(null);
const handelUserVipSubmitLoading = ref<boolean>(false);
const userVipForm = ref({
  uId: <number[] | string[]>[],
  vipId: null,
  remark: null,
  price: null,
})

//设定vip
const showUserVipSetting = () => {
  if (userVipForm.value.uId.length === 0) {
    message.warning('先请选择设定VIP的用户');
    return false;
  }
  userVipModel.value = true;
}
//选中的用户
const checkedUsers = (values: number[] | string[]) => userVipForm.value.uId = values;
const saveUserVip = (e: MouseEvent) => {
  e.preventDefault();
  userVipFormRef.value?.validate((errors) => {
    if (!errors) {
      handelUserVipSubmitLoading.value = true;
      postPutRequest('user/save_vip', userVipForm.value).then((result: ResponseResult) => {
        if (result.code === 200) {
          message.success(result.message, {
            duration: 1500,
            onLeave() {
              userVipModel.value = false;
              data_list.value.cancelCheckData();
              data_list.value.reload();
            }
          })
        } else {
          message.error(result.message);
          handelUserVipSubmitLoading.value = false;
        }
      })
    }
  })
}
//选中确认出生日
const confirmBirthday = (value: number) => {
  const date = new Date(value);
// 调整时区偏差
  const userTimezoneOffset = date.getTimezoneOffset() * 60000;
  const adjustedDate = new Date(date.getTime() - userTimezoneOffset);
  addEditForm.value.birthday = adjustedDate.toISOString().split('T')[0];
}
//查询
const handleSubmitSearch = () => {
  data_list.value.searchListData();
}
//修改余额
const handelEditUserMoney = (record: Recordable) => {
  userMoneyForm.value.userId = record.id;
  userMoneyForm.value.userName = record.nickname;
  userMoneyForm.value.avatar = record.avatar;
  userMoneyForm.value.originalBalance = record.money;
  userMoneyModel.value = true;
}
//修改用户余额
const handelSubmitUserMoney = (e: MouseEvent) => {
  e.preventDefault();
  userMoneyFormRef.value?.validate((errors) => {
    if (!errors) {
      userMoneyHandelSubmitLoading.value = true;
      postPutRequest('user/edit_user_money', userMoneyForm.value).then((result: ResponseResult) => {
        if (result.code === 200) {
          message.success(result.message, {
            duration: 1500,
            onLeave() {
              userMoneyModel.value = false;
              data_list.value.reload();
            }
          })
        } else {
          message.error(result.message);
          userMoneyHandelSubmitLoading.value = false;
        }
      })
    }
  })
}
//修改
const handleEdit = (record: Recordable) => {
  addEditForm.value.id = record.id;
  addEditForm.value.nickname = record.nickname;
  addEditForm.value.phone = record.phone;
  addEditForm.value.sex = record.sex;
  addEditForm.value.avatar = record.avatar;
  addEditForm.value.birthday = record.birthday;
  addEditForm.value.integral = record.integral;
  addEditForm.value.money = record.money;
  addEditForm.value.status = record.status;
  addEditForm.value.intro = record.intro;
  addEditForm.value.totalWithdrawal = record.totalWithdrawal;
  addEditForm.value.birthdayStamp = record.birthday ? new Date(record.birthday).getTime() : null;
  addEditModel.value = true;
}
//删除用户
const handleDelete = (record: Recordable) => {
  delRequest('user/del', record.id).then((result: ResponseResult) => {
    if (result.status === 0 && result.code === 200) {
      message.success(result.message, {
        duration: 1500,
        onLeave() {
          data_list.value.reload();
        }
      })
    } else {
      message.error(result.message);
    }
  })
}
//修改用户信息
const handelSubmitData = (e: MouseEvent) => {
  e.preventDefault();
  handelSubmitLoading.value = true;
  postPutRequest('user/edit', addEditForm.value, 'PUT').then((result: ResponseResult) => {
    if (result.code === 200) {
      message.success(result.message, {
        duration: 1500,
        onLeave() {
          addEditModel.value = false;
          data_list.value.reload();
        }
      })
    } else {
      message.error(result.message);
      handelSubmitLoading.value = false;
    }
  })
}
const closeAddEditModel = () => {
  addEditForm.value.id = 0;
  addEditForm.value.nickname = null;
  addEditForm.value.phone = null;
  addEditForm.value.sex = null;
  addEditForm.value.avatar = null;
  addEditForm.value.birthday = null;
  addEditForm.value.integral = null;
  addEditForm.value.money = null;
  addEditForm.value.status = 0;
  addEditForm.value.intro = null;
  addEditForm.value.totalWithdrawal = null;
  addEditForm.value.birthdayStamp = null;
  handelSubmitLoading.value = false;
}
const closeUserMoneyModel = () => {
  userMoneyForm.value.userId = 0;
  userMoneyForm.value.userName = null;
  userMoneyForm.value.avatar = null;
  userMoneyForm.value.money = null;
  userMoneyForm.value.remark = null;
  userMoneyForm.value.type = null;
  userMoneyHandelSubmitLoading.value = false;
}
const getVipForSelect = () => {
  getRequest('vip/for_select').then((res: ResponseResult) => {
    const {data} = res;
    vipOptions.value = data;
  })
}

onMounted(() => {
  getVipForSelect();
})
</script>

<style scoped lang="scss">

</style>